package com.game;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import java.util.*;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
//按钮监听器
public class BtnListener implements ActionListener {

	private JDialog dialog;
	private List<GameButton> btnList=GamePanel.getBtnList();//获取按钮集合
	private List<Map<String,Object>> overList=SplitImage.smallImageList;//检验拼图是否完成
	// 交换图片
	@Override
	public void actionPerformed(ActionEvent event) {
		GameButton sourcBtn = (GameButton) event.getSource();//获取事件源按钮
		int sourceIndex=sourcBtn.getBtnIndex();					//事件源按钮索引
		boolean sourceHasIcon=sourcBtn.getHasIcon(); 				//事件源按钮是否有图片
		Icon sourceIcon=sourcBtn.getIcon();//事件源图片
		//事件源按钮 坐标
		int sourceY=sourceIndex/3;
		int sourceX=sourceIndex%3;
		
		//播放 点击 音效
		GameMusic.playClick();
		//换图
		if(sourceHasIcon){//事件源 有图
			for(int i=0;i<btnList.size();i++){
				GameButton targetBtn=btnList.get(i);
				//排除事件源按钮
				if(!targetBtn.equals(sourcBtn)){
					int targetIndex=targetBtn.getBtnIndex();
					//目标按钮坐标
					int targetY=targetIndex/3;
					int targetX=targetIndex%3;
					//交换条件
					if(Math.abs(sourceY-targetY)+Math.abs(sourceX-targetX)==1){
						if(targetBtn.getHasIcon()==false){//寻找 集合中无图按钮 做交换
							System.out.println(sourcBtn.getIcon());
							//交换图片
							sourcBtn.setIcon(null);
							sourcBtn.setHasIcon(false);
							
							targetBtn.setIcon(sourceIcon);
							targetBtn.setHasIcon(true);
							
							//overList交换元素位置
							Collections.swap(overList, sourceIndex, targetBtn.getBtnIndex());
							
							break;//跳出循环
						}
					}				
				}
			}
		}
		//检查是否完成
		isOk();

	}
	
	//是否 赢了
	public boolean isOk(){
		boolean isOk=true;
		for(int i=0;i<overList.size();i++){
			Map<String,Object> map=(Map<String, Object>)overList.get(i);
			int index=Integer.parseInt(map.get("index").toString());
			if(index!=i){
				isOk=false;
			}
		}
		if(isOk){
			if(dialog==null){
				dialog=new JDialog();
			}
			dialog.setModal(true);
			dialog.setTitle("恭喜你，完成了拼图");
			JPanel panel=new JPanel();
			JLabel label=new JLabel("恭喜，游戏完成!!!");
			label.setFont(new Font("宋体", 1, 35));
			panel.add(label);
			dialog.add(panel);
			dialog.setLocation(300, 200);
			dialog.setSize(600, 400);
			dialog.show();
		}
		return isOk;
	}
	
}
